use crate::handler::handler::send_response;
use crate::model::device;
use crate::model::request::{DeviceInfo, DeviceSearch, ID};
use crate::pkg::errno::code::Errno::{ErrDatabase, ErrDeviceNotFound, IsOk};
use actix_web::{web, Responder, Result};

// 增加
pub async fn create(params: web::Json<DeviceInfo>) -> Result<impl Responder> {
    let res = device::create_device(&params).await;
    match res {
        Ok(_) => send_response(IsOk, Some(())).await,
        Err(_) => send_response(ErrDatabase, None).await,
    }
}

// 编辑
pub async fn edit(params: web::Json<DeviceInfo>) -> Result<impl Responder> {
    // 判断id 是否存在
    if params.id.is_some() {
        // 查询 id是否存在
        let resp = device::device_detail(params.id.unwrap()).await;
        match resp {
            Ok(_) => {
                let edit_res = device::edit_device(&params).await;
                match edit_res {
                    Ok(_) => send_response(IsOk, Some(())).await,
                    Err(_) => send_response(ErrDatabase, None).await,
                }
            }
            Err(_) => send_response(ErrDeviceNotFound, None).await,
        }
    } else {
        send_response(ErrDeviceNotFound, None).await
    }
}

// 删除
pub async fn delete(params: web::Path<ID>) -> Result<impl Responder> {
    // 查询 id是否存在
    let resp = device::device_detail(params.id).await;
    match resp {
        Ok(_) => {
            let delete_res = device::delete_device(params.id).await;
            match delete_res {
                Ok(_) => send_response(IsOk, Some(())).await,
                Err(_) => send_response(ErrDatabase, None).await,
            }
        }
        Err(_) => send_response(ErrDeviceNotFound, None).await,
    }
}

// 查询 详情
pub async fn detail(params: web::Path<ID>) -> Result<impl Responder> {
    let res = device::device_detail(params.id).await;
    match res {
        Ok(i) => send_response(IsOk, Some(i)).await,
        Err(_) => send_response(ErrDeviceNotFound, None).await,
    }
}

// 查询列表
pub async fn get_device_list_handler(params: web::Query<DeviceSearch>) -> Result<impl Responder> {
    println!("list {:#?}", params);
    let res = device::get_device_list_model(&params).await;
    match res {
        Ok(i) => send_response(IsOk, Some(i)).await,
        Err(_) => send_response(ErrDatabase, None).await,
    }
}
